package com.jjh.winterframework.core;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.jjh.winterframework.util.WinterUtils;

/**
 * 模拟spring制作一个winter框架
 * spring是春天的意思，
 * 那么winter就是冬天的意思
 * @author JJH
 *
 *         winterframework
 *
 */
public class ApplicationContext {

    /**
     * 最核心的应该是bean的map集合了
     */
    private static Map<String,Object> beanMap = new ConcurrentHashMap<>();

    public ApplicationContext(){

    }

    /**
     * 模拟run方法
     */
    public static ApplicationContext run(){
        //WinterUtils.printWinterLogo();

        System.out.println("LOG: "+WinterUtils.getNowTime()+":   winterframework start success!");

        ApplicationContext context = new ApplicationContext();
        //先把注解解析类注册为bean
        context.registerBean("annotationProcess",new CommonAnnotationProcess());
        context.registerBean("autowiredProcess",new AutoWiredProcess());
        return context;
    }

    /**
     * 向map中添加bean
     * @param beanName bean名称
     * @param bean bean对象
     * @return 是否添加成功
     */
    public boolean registerBean(String beanName,Object bean){
        beanMap.put(beanName,bean);
        return true;
    }

    /**
     * 根据类型获取bean对象
     * @param clazz
     * @return
     */
    public Object getBean(Class<?> clazz){
        String clazzName = clazz.getName();
        Object[] objects = new Object[1];
        beanMap.forEach((name,bean)->{
            if(bean.getClass().getName().equals(clazzName)){
               objects[0] = bean;
            }
        });
        return objects[0];
    }
    /**
     * 根据bean的名称获取bean对象
     */
    public Object getBean(String name){
        Object[] objects = new Object[1];
        beanMap.forEach((id,bean)->{
           if(id.equals(name)){
               objects[0] = bean;
           }
        });
        return objects[0];
    }

    /**
     * 通过静态方法获取bean对象
     * @return
     */
    public static Map<String,Object> getBeans(){
        return beanMap;
    }

    /**
     * 通过this获取
     * @return
     */
    public Map<String,Object> getAllBean(){
        return beanMap;
    }

    /**
     * 静态方法获取bean
     * @param clazz
     * @return
     */
    public static Object GetBean(Class<?> clazz){

        Object[] objects = new Object[1];
        Map<String, Object> beans = getBeans();
        beans.forEach((k,v)->{
            if(v.getClass().equals(clazz)){
                objects[0] = v;
            }
        });
        return objects[0];
    }


}
